package com.bosssoft.cloud.wechat.infrastructure.processor;

import com.alibaba.fastjson.annotation.JSONField;
import com.bosssoft.cloud.wechat.infrastructure.annotation.RequestParams;
import com.bosssoft.cloud.wechat.infrastructure.enums.ErrEnum;
import com.bosssoft.cloud.wechat.infrastructure.exception.BusinessException;
import com.bosssoft.cloud.wechat.infrastructure.util.ReflectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

/**
 * RequestParams的HandlerMethod方法参数解析器
 * 对RequestParams注解标注的入参进行参数解析映射
 *
 * @author wcy create on 2021/7/27 16:34 下午
 */
@Slf4j
@Component
public class RequestParamsMethodProcessor implements HandlerMethodArgumentResolver {

    private static final String SET = "set";

    /**
     * 判断本HandlerMethodArgumentResolver是否支持 MethodParameter
     *
     * @param parameter 方法参数
     * @return 是否调用调用resolveArgument()
     */
    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(RequestParams.class);
    }

    /**
     * 具体解析参数方法
     *
     * @param parameter     方法参数
     * @param mavContainer  上下文容器
     * @param webRequest    HttpServletRequest
     * @param binderFactory webDataBinder工厂类，把web请求的parameters绑定到JavaBean上
     * @return 解析后的入参实体
     */
    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        Class<?> clazz = parameter.getParameterType();
        Object target;
        try {
            target = processFiledValue(webRequest, clazz);
        } catch (Exception e) {
            throw new BusinessException(ErrEnum.A0402);
        }
        return target;
    }

    /**
     * 处理请求参数值
     *
     * @param webRequest HttpServletRequest
     * @param clazz      clazz
     */
    private Object processFiledValue(NativeWebRequest webRequest, Class<?> clazz) throws Exception {
        Object target = clazz.newInstance();
        List<Field> declaredFields = ReflectUtil.getFieldsCallSuper(clazz);
        // 遍历field并根据规则赋值
        for (Field declaredField : declaredFields) {
            // 获取JSONField注解
            // 后面按照field的name,注解的name值,alternateNames的值的优先级，与request的参数匹配
            JSONField annotation = declaredField.getAnnotation(JSONField.class);
            // 直接匹配field的name(ps:为了效率写得有点糟)
            String value = getParamValue(webRequest, declaredField.getName());
            // 若无法匹配，则匹配JSONField.name
            if (StringUtils.isEmpty(value)) {
                value = getParamValue(webRequest, annotation.name());
            }
            // 若无法匹配，则匹配JSONField.alternateNames
            if (StringUtils.isEmpty(value)) {
                for (String s : annotation.alternateNames()) {
                    value = getParamValue(webRequest, s);
                    if (!StringUtils.isEmpty(value)) break;
                }
            }
            // 匹配不到，代表入参无此属性
            if (StringUtils.isEmpty(value)) continue;
            // 参数值类型转换
            Object parseObj = ReflectUtil.processFiledType(declaredField, value);
            // 赋值
            ReflectUtil.set(target, declaredField.getName(), parseObj);
        }
        return target;
    }

    /**
     * 参数值类型转换
     *
     * @param declaredField field
     * @param value         要转换的值
     * @return 转换后的值
     */
    private Object processFiledType(Field declaredField, String value) {
        Object resultValue = value;
        String fieldType = declaredField.getType().getName();
        try {
            if (Objects.equals(fieldType, Integer.class.getName())) {
                resultValue = Integer.valueOf(value);
            } else if (Objects.equals(fieldType, String.class.getName())) {
                resultValue = value;
            } else if (Objects.equals(fieldType, Byte.class.getName())) {
                resultValue = Byte.valueOf(value);
            } else if (Objects.equals(fieldType, Long.class.getName())) {
                resultValue = Long.valueOf(value);
            } else if (Objects.equals(fieldType, Double.class.getName())) {
                resultValue = Double.valueOf(value);
            }
        } catch (Exception e) {
            throw new BusinessException(ErrEnum.A0402);
        }
        return resultValue;
    }

    /**
     * 获取set方法名
     *
     * @param name 属性名
     * @return 属性对应的set方法名
     */
    private String getSetMethodName(String name) {
        return SET + name.substring(0, 1).toUpperCase() + name.substring(1);
    }

    /**
     * 获取请求的参数
     *
     * @param webRequest request
     * @param fieldName  参数名
     * @return 参数值
     */
    private String getParamValue(NativeWebRequest webRequest, String fieldName) {
        return webRequest.getParameter(fieldName);
    }
}

